package com.gxf.drugmg.service;

import com.gxf.drugmg.entity.DrugRecognition;
import com.gxf.drugmg.repository.DrugRecognitionRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Random;
import java.util.UUID;

@Service
public class DrugRecognitionService {
    
    @Autowired
    private DrugRecognitionRepository recognitionRepository;
    
    private final String uploadDir = "uploads/";
    
    public DrugRecognition recognizeDrugs(MultipartFile file) throws IOException {
        // 创建上传目录
        File directory = new File(uploadDir);
        if (!directory.exists()) {
            directory.mkdirs();
        }
        
        // 保存文件
        String fileName = UUID.randomUUID().toString() + "_" + file.getOriginalFilename();
        Path filePath = Paths.get(uploadDir + fileName);
        Files.write(filePath, file.getBytes());
        
        // 模拟药品识别（实际项目中可以集成AI识别服务）
        RecognitionResult result = simulateDrugRecognition(fileName);
        
        // 保存识别结果
        DrugRecognition recognition = new DrugRecognition(
            fileName,
            result.getDrugNames(),
            result.getCount(),
            result.getConfidence()
        );
        
        return recognitionRepository.save(recognition);
    }
    
    public List<DrugRecognition> getAllRecognitions() {
        return recognitionRepository.findByOrderByRecognizedAtDesc();
    }
    
    public DrugRecognition getRecognitionById(Long id) {
        return recognitionRepository.findById(id).orElse(null);
    }
    
    // 模拟药品识别算法
    private RecognitionResult simulateDrugRecognition(String fileName) {
        Random random = new Random();
        
        // 模拟识别的药品名称
        String[] drugNames = {
            "阿莫西林胶囊", "布洛芬片", "维生素C片", "感冒灵颗粒", 
            "头孢克肟胶囊", "板蓝根颗粒", "复方甘草片", "氨茶碱片"
        };
        
        // 随机选择1-3种药品
        int drugTypeCount = random.nextInt(3) + 1;
        StringBuilder recognizedDrugs = new StringBuilder();
        int totalCount = 0;
        
        for (int i = 0; i < drugTypeCount; i++) {
            String drugName = drugNames[random.nextInt(drugNames.length)];
            int count = random.nextInt(10) + 1; // 1-10个
            totalCount += count;
            
            if (i > 0) recognizedDrugs.append(", ");
            recognizedDrugs.append(drugName).append("(").append(count).append("个)");
        }
        
        double confidence = 0.75 + random.nextDouble() * 0.2; // 75%-95%的置信度
        
        return new RecognitionResult(recognizedDrugs.toString(), totalCount, confidence);
    }
    
    // 内部类用于封装识别结果
    private static class RecognitionResult {
        private String drugNames;
        private int count;
        private double confidence;
        
        public RecognitionResult(String drugNames, int count, double confidence) {
            this.drugNames = drugNames;
            this.count = count;
            this.confidence = confidence;
        }
        
        public String getDrugNames() { return drugNames; }
        public int getCount() { return count; }
        public double getConfidence() { return confidence; }
    }
}